package com.lxw.station.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxw.station.entity.GitProject;
import com.lxw.station.service.RestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class GitXxApi {
    private static List<String> blacklist = Arrays.asList("cirosantilli");

    public static void main(String[] args) {
        List<GitProject> stringBoot = giteeProjects("StringBoot");
        for (GitProject gitProject : stringBoot) {
            System.out.println(JSON.toJSONString(gitProject));
        }
    }

    public static List<GitProject> giteeProjects(String q) {
        String urlMb = "https://api.indexea.com/v1/search/widget/wjawvtmm7r5t25ms1u3d?query=1048&q=${q}&from=${from}&size=10&sort_by_f=";
        int from = 0;
        String url = urlMb.replace("${q}", q).replace("${from}", String.valueOf(from));
        List<GitProject> projects = new ArrayList<>();
        String exchange = RestTemplateService.exchange(url, HttpMethod.GET);
        JSONArray hits = JSON.parseObject(exchange).getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject fields = hits.getJSONObject(i).getJSONObject("fields");
            String title = fields.getJSONArray("title").toJavaList(String.class).get(0);
            if (blacklist.contains(title.substring(0, title.indexOf("/")))) {
                continue;
            }
            String description = fields.getJSONArray("description").toJavaList(String.class).get(0);
            if (!StringUtils.hasText(description)) {
                continue;
            }
            GitProject project = new GitProject();
            project.setKeyWord(q);
            project.setProjectType(1);
            project.setProjectId(fields.getJSONArray("id").toJavaList(String.class).get(0));
            project.setProjectTitle(title);
            project.setProjectName(title.substring(title.indexOf("/") + 1));
            project.setProjectDescription(description);
            project.setProjectUrl(fields.getJSONArray("url").toJavaList(String.class).get(0));
            JSONArray langs = fields.getJSONArray("langs");
            if (!CollectionUtils.isEmpty(langs)) {
                project.setProjectLangs(JSON.toJSONString(langs.toJavaList(String.class)));
            }
            project.setProjectStar(fields.getJSONArray("count.star").toJavaList(String.class).get(0));
            project.setProjectStatus("待下载");

            String zipDescription = removeEmojis(description);
            if (zipDescription.length()>500) {
                zipDescription = zipDescription.substring(0,499);
            }
            project.setZipDescription(zipDescription);
            String zipName = sanitizeFilename(zipDescription);
            if (zipName.length()<59-q.length()) {
                zipName = q+"："+zipName;
            }
            if (zipName.length()>60) {
                zipName = zipName.substring(0,59);
            }
            project.setZipName(zipName);
            projects.add(project);
        }
        return projects;
    }

    /**
     * 替换掉文件名称不支持的符号
     * @param s
     * @return
     */
    private static String sanitizeFilename(String s) {
        // 文件名 不支持的字符列表
        String[] invalidChars = {"\\", "/", ":", "*", "?", "\"", "<", ">", "|"};
        // 替换不支持的字符为空字符串
        for (String invalidChar : invalidChars) {
            s = s.replace(invalidChar, "");
        }
        return s;
    }

    /**
     * 替换掉表情
     * @param s
     * @return
     */
    private static String removeEmojis(String s) {
        // 替换掉标题中的表情
        s = s.replaceAll("[\\p{So}\\p{Cn}\\uD83C\\uDF00-\\uD83D\\uDDFF\\uD83E\\uDD00-\\uD83E\\uDFFF]", "");
        s = s.replace("<em>", "").replace("</em>", "");
        return s;
    }
}
